<template>
  <div>
    <div class="pageCard">
      <a-form layout="inline" :model="formSearch" style="align-items: center">
        <a-form-item>
          <a-select
            allowClear
            style="width: 200px"
            v-model:value="formSearch.roleId"
            placeholder="请选择所属角色"
          >
            <a-select-option
              v-for="item in roleListValue"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-tree-select
          allowClear
            v-model:value="formSearch.hospitalDepartId"
            style="width: 200px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="departmentList"
            placeholder="请选择科室"
            tree-default-expand-all
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item>
          <a-input
          allowClear
            v-model:value="formSearch.realName"
            placeholder="请输入真实姓名"
          >
          </a-input>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="getSearch">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="toresetFields">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div style="background: #fff">
      <a-table
        style="padding: 0 20px"
        :pagination="pagination"
        :columns="columns"
        :rowKey="(record) => record.id"
        :data-source="list"
        :row-selection="rowSelection"
      >
        <template #operation="{ record }">
          <div style="display: flex; align-items: center">
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_blue"
              @click="lookHandle(record)"
            >
              查看
            </div>
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_blue"
              @click="editHandle(record)"
            >
              编辑
            </div>
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_blue"
              @click="handleGenerateQrCode(record)"
            >
              下载二维码
            </div>
            <div
              style="cursor: pointer; padding: 0 4px"
              class="color_red"
              @click="delHandle(record)"
            >
              删除
            </div>
          </div>
        </template>
        <template #title>
          <div class="ANTTable_header">
            <div style="font-weight: bold">人员信息维护</div>
            <div>
              <a-button @click="handleImport" style="margin: 0 10px"
                >导入人员</a-button
              >
              <a-button @click="handleExport" style="margin: 0 10px"
                >批量导出</a-button
              >
              <a-button @click="handleDownloadCode" style="margin: 0 10px"
                >批量下载二维码</a-button
              >

              <a-button type="primary" @click="addHandle('')"
                >添加人员</a-button
              >
            </div>
          </div>
        </template>
      </a-table>
    </div>

    <a-modal
      width="40%"
      v-model:visible="visible"
      :title="handleTitle"
      @ok="handleOk"
      @cancel="handleCancle"
      ok-text="确认"
      cancel-text="取消"
    >
      <child
        v-if="visible"
        :handleType="handleType"
        :handleRow="handleRow.data"
        ref="child"
        @finish="finishHandle"
      ></child>
    </a-modal>

    <a-modal
      width="40%"
      v-model:visible="ImportFilevisible"
      title="导入人员"
      @ok="ImporthandleOk"
      ok-text="确认上传"
      cancel-text="取消"
    >
      <a-upload-dragger  accept="application/vnd.ms-excel" :before-upload="beforeUpload" v-model:fileList="fileList" name="file" >
        <p class="ant-upload-drag-icon">
          <inbox-outlined></inbox-outlined>
        </p>
        <a-button @click.stop="ImporthandleCancle()">下载模板</a-button>
        <p class="ant-upload-text">第一步:下载Excel人员模板;</p>
        <p class="ant-upload-text">
          第二步:使用模板编辑人员,点击"选择文件"选择您编辑好的Excel文档;
        </p>
        <p class="ant-upload-text">第三步:点击"确认上传"完成人员导入;</p>
      </a-upload-dragger>
    </a-modal>
  </div>
</template>
<script>
import child from "./components/child.vue";
import { createVNode, onMounted, reactive, ref, toRefs, watch } from "vue";
import * as utils from "@/utils/index.js";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { Form } from "ant-design-vue";
import { Modal, message } from "ant-design-vue";
import { getUserInfo } from "@/utils/auth";
import { roleList } from "@/api/setting1.js";
import * as department from "@/api/department.js";
import { hospitalDepartList } from "@/api/hospitalDepart.js";
// 表格Column
const columns = [
  {
    title: "真实姓名",
    dataIndex: "realName",
  },
  {
    title: "角色名称",
    dataIndex: "roleName",
  },
  {
    title: "科室名称",
    dataIndex: "hospitalDepartName",
  },
  {
    title: "手机号码",
    dataIndex: "mobile",
  },
  {
    title: "身份证号码",
    dataIndex: "idNumber",
  },
  {
    title: "工号",
    dataIndex: "jobNumber",
  },
  {
    title: "常用邮箱",
    dataIndex: "email",
  },

  {
    title: "操作",
    dataIndex: "operation",
    width: 250,
    slots: { customRender: "operation" },
  },
];
const useForm = Form.useForm;
export default {
  components: {
    child,
    ExclamationCircleOutlined,
  },
  setup(props, { emit }) {
    const formSearch = reactive({
      realName: "",
      // 人员
      hospitalDepartId: null,
      // 角色
      roleId: null,
    });
    const userInfo = ref(getUserInfo() ? JSON.parse(getUserInfo()) : {});
    const tableData = reactive({ list: [], total: 0 });
    const { resetFields } = useForm(formSearch);
    const pageSize = ref(10);
    const pageIndex = ref(1);
    // 查询
    const getSearch = () => {
      console.log(333)
      pageIndex.value = 1;
      pagination.current = 1
      handleGetDataList();
    };
    const roleListValue = ref([]);
    //获取角色列表
    const handleGetRoleList = () => {
      roleList({ isPage: false }).then((res) => {
        if (res && res.success) {
          roleListValue.value = res.data;
        }
      });
    };

    const pagination = reactive({
      total: 0,
      current:pageIndex.value,
      pageSize: pageSize.value, // 默认每页显示数量
      showSizeChanger: true, // 显示可改变每页数量
      pageSizeOptions: ["10", "20", "30", "40"], // 每页数量选项
      showTotal: (total) => `总数 ${total}条数据`, // 显示总数
      onChange: (page, size) => {
        onPageChange(page, size);
      }, // 改变每页数量时更新显示
      onShowSizeChange: (current, size) => {
        onSizeChange(current, size);
      },
    });
    // 分页
    const onSizeChange = (current, size) => {
      pageIndex.value = 1;
      pagination.current = 1
      pageSize.value = size;
      handleGetDataList();
    };
    const onPageChange = (current, size) => {
      pageIndex.value = current;
      pagination.current = current
      handleGetDataList();
    };
    // 获取表格
    const handleGetDataList = async () => {
      tableData.list = [];
      let params = {
        ...formSearch,
       pageIndex:pageIndex.value,
       pageSize:pageSize.value,
      };
      department.sysUserStaffList(params).then((res) => {
        if (res && res.success) {
          console.log(123);
          console.log(res);
          tableData.list = res.data;
          pagination.total = res.total;
        }
      });
    };
    const tableSelectedRows = ref([]);
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        tableSelectedRows.value = selectedRows;
      },
      onSelect: (record, selected, selectedRows) => {
        console.log(record, selected, selectedRows);
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        console.log(selected, selectedRows, changeRows);
      },
    };
 const beforeUpload = ()=>{
      return false
    }
    // 重置表格
    const toresetFields = () => {
      resetFields();
      getSearch();
    };
    // 监听表格
    watch(
      () => formSearch,
      (curAge, preAge) => {
        getSearch();
      },
      { deep: true }
    );
    // 获取人员数据
    const departmentList = ref([]);
    const getKSData = async () => {
      let res = await hospitalDepartList({
        isPage: false,
        name: "",
      });
      if (res && res.success) {
        let departmentListO = res.data.map((item) => {
          item.label = item.name;
          item.value = item.id;
          return item;
        });
        departmentList.value = utils.treeDataTranslate(departmentListO);
        console.log(123444444);
        console.log(departmentList.value);
      }
    };
    //  新增功能
    const visible = ref(false);
    const handleType = ref("add");
    const handleTitle = ref("新增人员");
    const handleRow = reactive({ data: {} });
    const addHandle = (row) => {
      visible.value = true;
      handleType.value = "add";
      handleTitle.value = row ? "新增下级人员" : "新增人员";
      console.log(row);
      if (!row) {
        handleRow.data = {
          parentId: "",
        };
      } else {
        handleRow.data = {
          parentName: row.name,
          parentId: row.id,
        };
      }
    };
    const lookHandle = (data) => {
      visible.value = true;
      handleType.value = "look";
      handleTitle.value = "查看人员";
      handleRow.data = {
        ...data,
      };
    };
    const editHandle = (data) => {
      visible.value = true;
      handleType.value = "edit";
      handleTitle.value = "编辑人员";
      handleRow.data = {
        ...data,
      };
    };
    // 删除
    const delHandle = (data) => {
      Modal.confirm({
        title: () => "提示",
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () =>
          createVNode("div", { style: "color:red;" }, "确认删除该人员"),
        onOk() {
          department.sysUserStaffRemove(data.id).then((res) => {
            if (res && res.success) {
              message.success("删除成功");
              getSearch();
            }
          });
        },
        onCancel() {
          console.log("Cancel");
        },
        class: "test",
      });
    };
    //导入
    const handleImport = () => {
      ImportFilevisible.value = true;
    };
    // 批量导出
    const handleExport = () => {
      if (tableSelectedRows.value.length <= 0) {
        message.warning("请选择数据");
        return false;
      }
      let params = tableSelectedRows.value.map((item) => {
        return item.id;
      });
      department.exportList({ids:params}).then((res) => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "application/vnd.ms-excel", // "application/zip",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = "人员"; // 下载后文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    };
    //批量下载二维码
    const handleDownloadCode = () => {
      if (tableSelectedRows.value.length <= 0) {
        message.warning("请选择数据");
        return false;
      }
      let params = tableSelectedRows.value.map((item) => {
        return item.id;
      });
      department.generateQrCodeBatch(params).then((res) => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "application/zip", // "application/zip",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = "人员"; // 下载后文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        message.success("操作成功");
      });
    };
    //下载二维码
    const handleGenerateQrCode = (row) => {
      department.generateQrCode(row.id).then((res) => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "image/png", // "application/zip",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = row.realName; // 下载后文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    };
    // 完成操作
    const finishHandle = () => {
      visible.value = false;
      getSearch();
    };

    const child = ref(null);
    const handleOk = () => {
      child.value.handleSave();
    };

    const handleCancle = () => {
      child.value.resetForm();
    };

    // 导入功能
    const ImportFilevisible = ref(false);
    const fileList = ref([]);

    const ImporthandleOk = () => {
      console.log(fileList.value[0].originFileObj);
      let formDate = new FormData();
      formDate.append("file", fileList.value[0].originFileObj);
      department.importList(formDate).then((res) => {
        if (res && res.success) {
          message.success("导入成功");
          ImportFilevisible.value = false;
          getSearch();
        }
      });
    };

    const ImporthandleCancle = () => {
      department.downloadTemplate().then((res) => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "application/vnd.ms-excel", // "application/zip",
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = "人员"; // 下载后文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });

      return false;
    };
    onMounted(() => {
      handleGetDataList();
      handleGetRoleList();
      getKSData();
    });
    return {
      child, //子组件
      roleListValue,
      formSearch,
      toresetFields,
      beforeUpload,
      userInfo,
      columns,
      ...toRefs(tableData),
      handleGetDataList,
      getSearch,

      visible,
      addHandle,
      editHandle,
      lookHandle,
      handleTitle,
      handleRow,
      handleType,
      handleOk,
      handleCancle,
      finishHandle,

      delHandle,
      pagination,
      handleGenerateQrCode,
      handleDownloadCode,
      handleExport,

      ImportFilevisible,
      fileList,
      ImporthandleOk,
      ImporthandleCancle,
      handleImport,
      rowSelection,
      tableSelectedRows,

      departmentList,
      getKSData,
    };
  },
};
</script>